const db = require("../../database");
const writeLogs = require('./writeLogs');

module.exports = (req, res) => {
    let {friend, friends, messages} = req.body;
    const username = req.auth.username;
    friends = friends === '' ? friend : friends + ';' + friend;
    const msg = JSON.parse(messages);
    delete msg[friend]['add'];
    messages = JSON.stringify(msg);
    let sql = 'update users set friends = ?, messages = ? where username = ?';
    db.query(sql, [friends, messages, username], (err, data) => {
        if (err) {
            writeLogs('err', { err });
            return res.cc(err)
        }
        if (!data.affectedRows) return res.cc('数据更新失败')
        writeLogs('updateFriends', {
            username,
            friends,
        });
        sql = 'select friends, messages from users where username = ?';
        db.query(sql, friend, (err, data) => {
            if (err) {
                writeLogs('err', { err });
                return res.cc(err)
            }
            if (!data.length) return res.cc('对方数据更新失败');
            const newFriendList = data[0]['friends'] ? data[0]['friends']  + ';' + username :
                '' + username;
            const oldMessages = JSON.parse(data[0]['messages'] || '{}');
            if (oldMessages[username]) {
                oldMessages[username]['agr'] = '';
            } else {
                oldMessages[username] = {'agr': ''};
            }
            const newMessages = JSON.stringify(oldMessages);
            writeLogs('updateFriends', {
                friend,
                newFriendList,
            });
            sql = 'update users set friends = ?, messages = ? where username = ?';
            db.query(sql, [newFriendList, newMessages, friend], (err, data) => {
                if (err) {
                    writeLogs('err', { err });
                    return res.cc(err)
                }
                if (!data.affectedRows) return res.cc('数据更新失败')
                res.cc('添加成功', 0);
            })
        })
    })
}